<template>
  <div>
    <!-- 导航 -->
    <van-nav-bar title="黑马头条" />
    <!-- 表单 -->
    <!-- ^(\+?0?86\-?)?1[3-9]\d{9}$ -->
    <van-form @submit="onSubmit" @failed="onFailed">
      <van-field
        v-model.trim="user.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
          },
        ]"
      />
      <van-field
        v-model.trim="user.code"
        type="text"
        name="验证码"
        label="验证码"
        placeholder="验证码"
        :rules="[
          {
            pattern: /^\d{6}$/,
            message: '请输入正确的验证码',
          },
        ]"
      />
      <div style="margin: 16px" class="btn-wrap">
        <van-button
          class="van-button"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <!-- 按钮 -->
  </div>
</template>

<script>
// import {
//   login
//   //  getProfile
// } from '../../api/user'
export default {
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13800000002',
        code: '246810'
      }
    }
  },
  methods: {
    async doLogin () {
      this.$toast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      // 做具体的提交动作
      try {
        // 由于actions中有异步的操作，这里补充await
        // const { data: { data } } = await login(this.user)
        // console.log(data)
        // localStorage.setItem('token', 'Bearer ' + data.token)
        // console.log(1)

        // 获取token并保存在vuex中
        await this.$store.dispatch('setToken', this.user)
        // 调用命名空间的modules存储用户信息
        await this.$store.dispatch('user/getProfile')
        // console.log(4)
        this.$toast.success('登录成功')
        // 页面跳转(若有backto就用这个没有就返回主页)
        const backto = this.$route.query.backto
        this.$router.push(backto || '/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
    },
    onSubmit (values) {
      // console.log('submit', values)
      this.doLogin()
    },
    onFailed () {
      console.log('验证失败')
    }
  }
}
</script>

<style lang="less" scoped>
// 按钮
.btn-wrap {
  padding: 20px;
  .van-button {
    width: 100%;
    background-color: #6db4fd;
    color: #fff;
  }
}
</style>
